package 数组和链表;

import 抽象数据类型.ListNode;

public class 合并两个排序好的链表 {
    public static ListNode Merge(ListNode list1, ListNode list2) {
        if (list1 == null) {
            return list2;
        }
        if (list2 == null) {
            return list1;
        }
        ListNode mergeHead = null;
        ListNode current = null;
        while (list1 != null && list2 != null) {
            if (list1.val <= list2.val) {
                if (mergeHead == null) {
                    mergeHead = current = list1;

                } else {
                    current.next = list1;
                    current = current.next;
                    display(current);
                }
                list1 = list1.next;
            } else {
                if (mergeHead == null) {
                    mergeHead = current = list2;
                    display(current);

                } else {
                    current.next = list2;
                    current = current.next;
                    display(current);
                }
                list2 = list2.next;
            }
        }
        if (list1 == null) {
            current.next = list2;


        } else {
            current.next = list1;
            display(current.next);


        }

        return mergeHead;
    }

    public static void display(ListNode node) {
        while (node != null) {

            System.out.print(node.val + "\t");
            node = node.next;
        }
        System.out.println();
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ListNode node = new ListNode(4);
        node.next = new ListNode(5);
        node.next.next = new ListNode(8);
        display(node);
        ListNode node2 = new ListNode(3);
        node2.next = new ListNode(6);
        node2.next.next = new ListNode(7);
        display(node2);
        display(Merge(node, node2));
    }

}
